<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title>订单结算 - 优选商城</title>
    <style>
        .checkout-item {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }
        .checkout-item:last-child {
            border-bottom: none;
        }
        .checkout-item img {
            width: 80px;
            height: 80px;
            object-fit: cover;
        }
        .address-card {
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .address-card:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .address-card.selected {
            border-color: #0d6efd;
            box-shadow: 0 4px 12px rgba(13, 110, 253, 0.2);
        }
        .checkout-summary {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="container my-4">
            <h2 class="mb-4">订单结算</h2>
            
            <div class="row">
                <div class="col-md-8">
                    <!-- 收货地址 -->
                    <div class="card mb-4">
                        <div class="card-header bg-white">
                            <h5 class="mb-0">收货地址</h5>
                        </div>
                        <div class="card-body">
                            <div class="row" th:if="${not #lists.isEmpty(addressList)}">
                                <div class="col-md-6" th:each="address : ${addressList}">
                                    <div th:data-id="${address.id}" 
                                         th:class="${defaultAddress != null && defaultAddress.id == address.id ? 'card address-card selected' : 'card address-card'}"
                                         onclick="selectAddress(this)">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between">
                                                <h6 class="card-title" th:text="${address.receiver}">收件人</h6>
                                                <span class="badge bg-primary" th:if="${address.isDefault == 1}">默认</span>
                                            </div>
                                            <p class="card-text mb-1" th:text="${address.phone}">电话</p>
                                            <p class="card-text text-muted small" 
                                               th:text="${address.province} + ' ' + ${address.city} + ' ' + ${address.district} + ' ' + ${address.detail}">
                                                地址详情
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div th:if="${#lists.isEmpty(addressList)}">
                                <p class="text-center py-3">您还没有收货地址</p>
                                <div class="text-center">
                                    <a href="/user/profile#address" class="btn btn-primary">添加收货地址</a>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 商品清单 -->
                    <div class="card">
                        <div class="card-header bg-white">
                            <h5 class="mb-0">商品清单</h5>
                        </div>
                        <div class="card-body">
                            <div th:each="cart : ${cartList}" class="checkout-item">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <img th:src="${cart.product.mainImage}" class="img-thumbnail" 
                                             th:alt="${cart.product.name}">
                                    </div>
                                    <div class="col">
                                        <h6 th:text="${cart.product.name}">商品名称</h6>
                                        <div class="text-muted small" th:text="${cart.product.subtitle}">商品描述</div>
                                    </div>
                                    <div class="col-auto text-end">
                                        <div class="text-muted">
                                            <span th:text="${cart.quantity}">1</span> x 
                                            ¥<span th:text="${cart.product.price}">0.00</span>
                                        </div>
                                        <div class="text-danger fw-bold">
                                            ¥<span th:text="${cart.quantity * cart.product.price}">0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="card checkout-summary">
                        <div class="card-body">
                            <h5 class="card-title">订单信息</h5>
                            <div class="d-flex justify-content-between mb-2">
                                <span>商品金额:</span>
                                <span>¥<span th:text="${#numbers.formatDecimal(totalAmount, 1, 2)}">0.00</span></span>
                            </div>
                            <div class="d-flex justify-content-between mb-2">
                                <span>运费:</span>
                                <span>¥0.00</span>
                            </div>
                            <hr>
                            <div class="d-flex justify-content-between mb-3">
                                <span class="fw-bold">应付金额:</span>
                                <span class="text-danger fw-bold">¥<span th:text="${#numbers.formatDecimal(totalAmount, 1, 2)}">0.00</span></span>
                            </div>
                            <button id="submitOrderBtn" class="btn btn-danger w-100" onclick="submitOrder()">
                                提交订单
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script th:fragment="script">
        let selectedAddressId;
        
        $(document).ready(function() {
            // 初始化选中的地址
            const selected = $('.address-card.selected');
            if (selected.length > 0) {
                selectedAddressId = selected.data('id');
            }
            
            // 禁用提交按钮，如果没有选中地址
            updateSubmitButton();
        });
        
        // 选择收货地址
        function selectAddress(element) {
            $('.address-card').removeClass('selected');
            $(element).addClass('selected');
            selectedAddressId = $(element).data('id');
            
            // 更新提交按钮状态
            updateSubmitButton();
        }
        
        // 更新提交按钮状态
        function updateSubmitButton() {
            if (selectedAddressId) {
                $('#submitOrderBtn').prop('disabled', false);
            } else {
                $('#submitOrderBtn').prop('disabled', true);
            }
        }
        
        // 提交订单
        function submitOrder() {
            if (!selectedAddressId) {
                showToast('请选择收货地址', 'warning');
                return;
            }
            
            // 禁用提交按钮，防止重复提交
            $('#submitOrderBtn').prop('disabled', true).text('处理中...');
            
            // 发送请求创建订单
            $.ajax({
                url: '/order/submit',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    addressId: selectedAddressId
                }),
                success: function(res) {
                    console.log('订单创建结果:', res);
                    
                    if (res.code === 0 && res.data) {
                        showToast('订单创建成功', 'success');
                        // 跳转到支付页面
                        console.log('准备跳转到:', '/order/pay/' + res.data.orderNo);
                        setTimeout(function() {
                            // 确保orderNo有值且格式正确
                            if (res.data.orderNo) {
                            window.location.href = '/order/pay/' + res.data.orderNo;
                            } else {
                                showToast('订单号为空，无法跳转支付页面', 'danger');
                                $('#submitOrderBtn').prop('disabled', false).text('提交订单');
                            }
                        }, 1500);
                    } else {
                        showToast(res.msg || '创建订单失败', 'danger');
                        $('#submitOrderBtn').prop('disabled', false).text('提交订单');
                    }
                },
                error: function() {
                    showToast('请求失败，请重试', 'danger');
                    $('#submitOrderBtn').prop('disabled', false).text('提交订单');
                }
            });
        }
        
        // 显示提示
        function showToast(message, type) {
            const toastContainer = document.querySelector('.toast-container');
            if (!toastContainer) return;
            
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        <i class="bi bi-${type === 'success' ? 'check-circle' : type === 'warning' ? 'exclamation-triangle' : 'exclamation-circle'} me-2"></i>
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            
            bsToast.show();
            
            // 自动移除toast元素
            toast.addEventListener('hidden.bs.toast', function () {
                toast.remove();
            });
        }
    </script>
</body>
</html> 